#encoding:utf-8
#pip install flask-script
import time,sys,os,json,datetime,re
reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append('mymd')
from flask import Flask,request,render_template,redirect,url_for,session
from functools import wraps
from flask_script import Manager
from mymd import req,sql

#设置flask
app = Flask(__name__)
#app = Flask(__name__,template_folder="views", static_folder="assets")
app.config.from_envvar('FLASKR_SETTING',silent=True)
app.secret_key = 'DJFDK@426456ddioerpocPCSWJKJB@MN$klkj#==--'
#app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER          #设置上传目录
#app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  #设置上传限制16M
#manager = Manager(app)

#设置session过期时间
app.permanent = True
app.permanent_session_lifetime = datetime.timedelta(minutes=5)

#过滤器

#过滤器
def unix_time(tms):
    ts=time.strptime(tms,"%Y-%m-%d  %H:%M:%S")
    res=int(time.mktime(ts))
    return res

def date_time(utms):
    tms=time.localtime(utms)
    res= time.strftime("%Y-%m-%d %H:%M:%S",tms)
    return res

def date(utms):
    tms=time.localtime(utms)
    res= time.strftime("%Y-%m-%d",tms)
    return res

def str_to_int(strs):
    res=int(strs)
    return res

def to_float(args1):
    tt='%.'+str(1)+'f'
    res=tt % (float(str(args1)))
    return res

def check_type(strs):
    if type(strs) is str:return 'str'
    if type(strs) is int:return  'int'
    if type(strs) is list:return 'list'
    if type(strs) is dict:return 'dict'
    if type(strs) is tuple:return 'tuple'

def is_checked(strs):
    if strs:
        return "checked"
    else:
        return ""


env = app.jinja_env
env.filters['check_type']=check_type
env.filters['unix_time']=unix_time
env.filters['date_time']=date_time
env.filters['date']=date
env.filters['str_to_int']=str_to_int
env.filters['is_checked']=is_checked
env.filters['to_float']=to_float




#验证登录
def check_login(fn):
    @wraps(fn)
    def BtnPrv(*args,**kw):
        if not session.get('s',None):
            return redirect('/login')
        return fn(*args,**kw)
    return BtnPrv


#实例化数据库
#db=sql.Mysql('127.0.0.1','root','123456','dnsmasq',3306)
db=sql.Sqlite3('mydns-masq.db')
#sdb=sql.Sqlite3('./masq.db')
@app.route('/')
@check_login
def index():
    data= request
    print data
    print request.headers
    return  render_template('index.html')

@app.route('/masq')
@check_login
def masq():
    sqls="select * from domain"
    data=db.read(sqls,'')
    #res=sdb.read(sqls)
    #print res
    return  render_template('masq_index.html',data=data)

#一键更新
@app.route('/masq/update')
@check_login
def masq_update():
    sqls='select * from domain where status=0'
    data=db.read(sqls,())
    with open('dnsmasq-hosts','w+') as f:
        for i in data:
            if i:
                try:
                    f.write(i['ip']+ ' '+i['domain']+'\n')
                except:
                    f.close()
        f.close()
    #os.system('/etc/init.d/dnsmasq reload')
    return  redirect(url_for('masq'))



@app.route('/masq/add',methods=['GET','POST'])
@check_login
def masq_add():
    if request.method == 'GET':
        return render_template('masq_add.html')

    if request.method == 'POST':
        domain = request.form.get('domain')
        ip = request.form.get('ip')
        status = request.form.get('status')
        if domain and ip and status:
            sqls = "INSERT INTO `domain` (`domain`, `ip`, `status`,`create_time`) VALUES (?, ?, ?,?);"
            db.write(sqls, (domain,ip,int(status),int(time.time())))
        return redirect(url_for('masq_update'))


@app.route('/masq/edit',methods=['GET','POST'])
@check_login
def masq_edit():
    id = request.args.get('id')
    if request.method == 'GET':
        sqls="select * from domain where id=%s;"%int(id)
        data=db.read(sqls,'')
        print data
        if data:
            d=data[0]
            return render_template('masq_edit.html',d=d)
        else:
            return redirect(url_for('masq'))

    if request.method == 'POST':
        domain = request.form.get('domain')
        ip = request.form.get('ip')
        status = request.form.get('status')
        if id and domain and ip and status:
            sqls="UPDATE `domain` SET `domain`=?,`ip`=?,`status`=?,`update_time`=?  WHERE  `id`=?;"
            db.write(sqls,(domain, ip,int(status),int(time.time()),int(id)))
        return redirect(url_for('masq_update'))

@app.route('/masq/action')
@check_login
def masq_action():
    id=request.args.get('id')
    active=request.args.get('active')

    if id and active=='enable':
        sqls='update domain set `status`=? where id=?'
        db.write(sqls,(0,int(id)))
        return redirect(url_for('masq_update'))

    if id and active == 'disble':
        sqls = 'update domain set status=? where id=?'
        db.write(sqls, (1,int(id)))
        return redirect(url_for('masq_update'))

    if id and active == 'delete':
        sqls = 'delete from domain where id=%s'
        db.write(sqls%int(id),())
    return redirect(url_for('masq_update'))

#用户管理
@app.route('/user')
@check_login
def user():
    sqls="select * from user"
    d=db.read(sqls,())
    return  render_template('user.html',d=d)

@app.route('/user/add',methods=['GET','POST'])
@check_login
def user_add():
    if request.method == 'GET':
        return render_template('user_add.html')

    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        passwd = request.form.get('passwd')
        status = request.form.get('status')
        is_active = request.form.get('is_active')
        qx= request.form.get('qx')
        print name,email,passwd,status,is_active,qx
        if session['s']['qx']==1 and name and email and passwd and status and qx and is_active:
            sqls='insert into user (`name`,`email`,`passwd`,`status`,`is_active`,`qx`,`create_time`) values (?,?,?,?,?,?,?);'
            db.write(sqls, (name,email,passwd,int(status),int(is_active),int(qx),int(time.time())))
        return redirect(url_for('user'))

@app.route('/user/edit',methods=['GET','POST'])
@check_login
def user_edit():
    id = request.args.get('id')
    if request.method == 'GET':
        if id:
            try:
                res=db.read('select * from user where id=%s'%id,())
                d=res[0] if res else {}
            except:
                return redirect(url_for('user'))
        return render_template('user_edit.html',d=d)


    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        passwd = request.form.get('passwd')
        status = request.form.get('status')
        is_active = request.form.get('is_active')
        qx= request.form.get('qx')
        print name,email,passwd,status,is_active,qx
        print session['s']
        if (session['s']['qx']==1 or session['s']['id']==id) and name and email and passwd and status and qx and is_active:
            #sqls='insert into user (`name`,`email`,`passwd`,`status`,`is_active`,`qx`,`create_time`) values (?,?,?,?,?,?,?);'
            sqls='update user set `name`=?,`email`=?,`passwd`=?,`status`=?,`is_active`=?,`qx`=?,`update_time`=? where id=?;'
            db.write(sqls, (name,email,passwd,int(status),int(is_active),int(qx),int(time.time()),id))
        return redirect(url_for('user'))




@app.route('/user/action')
@check_login
def user_action():
    id=request.args.get('id')
    active=request.args.get('active')
    qx = request.args.get('qx')

    if id and active=='enable':
        sqls='update user set `status`=? where id=?'
        db.write(sqls,(0,int(id)))
        return redirect(url_for('user'))

    if id and active == 'disble':
        sqls = 'update user set status=? where id=?'
        db.write(sqls, (1,int(id)))
        return redirect(url_for('user'))

    if id and qx and active == 'delete':
        if int(qx)==1:return redirect(url_for('user'))
        sqls = 'delete from user where id=%s'
        db.write(sqls%int(id),())
    return redirect(url_for('user'))



@app.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    if request.method == 'POST':
        email=request.form.get('email')
        passwd=request.form.get('passwd')
        res=[]
        if email and passwd:
            sqls="select * from user where email=? and passwd=? and status=0 "
            res=db.read(sqls,(email,passwd))
        if res:
            session['s']=res[0]
            return redirect(url_for('masq'))
        else:
            return render_template('login.html')

@app.route('/logout')
def logout():
    session.pop('s')
    return redirect(url_for('masq'))

if __name__ == "__main__":
    app.run(host='0.0.0.0',debug=True)
    #manager.run()
    '''
    python hello.py shell#在flask应用上下文环境中运行python shell，方便测试和调试web环境
    python hello.py runserver#运行flask开发服务器，app.run()
    python hello.py -h#显示帮助信息
    python hello.py runserver --help

　　usage: hello.py runserver [-h] [-t HOST] [-p PORT] [--threaded]
　　[--processes PROCESSES] [--passthrough-errors] [-d]
　　[-r]

    python hello.py runserver -h 0.0.0.0 -p 80#这样就开启了本机的80端口，别的机器可以远程访问了
    '''